package formal.tree.recursion;

/**
 * 二叉树中第二小的节点
 *
 * @author DengYuan2
 * @create 2021-01-18 22:33
 */
public class E_671 {
    public static void main(String[] args) {
//        Integer[] a = {2, 2, 5, null, null, 5, 7};
        Integer[] a = {2, 2, 5, 2, 2, 5, 7};
//        Integer[] a = {2, 2, 2};
        TreeNode treeNode = TreeNode.generateTree(a);
        int res = findSecondMinimumValue(treeNode);
        System.out.println(res);
    }


    /**
     * 我的写法不行-大神的如下
     * @param root
     * @return
     */
    public static int findSecondMinimumValue(TreeNode root) {
        if (root == null) {
            return -1;
        }
        if (root.left==null&&root.right==null){
            return -1;
        }
        int left = root.left.val;
        int right = root.right.val;
        if (left==root.val){
            left=findSecondMinimumValue(root.left);
        }
        if (right==root.val){
            right=findSecondMinimumValue(root.right);
        }
        if (right!=-1&&left!=-1){
            return Math.min(left,right);
        }
        if (right!=-1){
            return right;
        }
        return left;

    }

}
